<?php

namespace tmcore\services;

use think\facade\Cache as CacheStatic;

class CacheService
{
    /**
     * 过期时间
     * @var int
     */
    protected static $expire;

    /**
     * 获取缓存过期时间
     * @param int|null $expire
     * @return mixed
     */
    protected static function getExpire($expire = null)
    {
        if (self::$expire) {
            return (int)self::$expire;
        }
        $expire = !is_null($expire) ? $expire : 0;
        if (!is_int($expire)) $expire = (int)$expire;
        return self::$expire = $expire;
    }

    /**
     * 缓存句柄
     * @param string $name 缓存标签名
     * @return object
     */
    public static function handler($name = "")
    {
        if($name) {
            return CacheStatic::tag($name);
        } else {
            return CacheStatic::store();
        }
    }

    /**
     * 写入缓存
     * @param string $name 缓存名称
     * @param mixed $value 缓存值
     * @param int $expire 缓存时间，0-为无限制，单位秒
     * @param string $tag 缓存标签
     * @return bool
     */
    public static function set($name, $value, $expire = 0, $tag = '')
    {
        return self::handler($tag)->set($name, $value, self::getExpire($expire));
    }

    /**
     * 获取缓存
     * @param string $name 缓存名称 (缓存标签不会改变缓存的读取)
     * @param string $default 默认缓存值
     * @param int $expire 过期时间，0-为无限制，单位秒
     * @return mixed
     */
    public static function get($name, $default = '', $expire = 0)
    {
        return self::handler()->remember($name, $default, self::getExpire($expire));
    }

    /**
     * 缓存自增
     * @param string $name 缓存名称
     * @param int $num 数量
     * @return mixed
     */
    public static function inc($name, $num = 0)
    {
        return self::handler()->inc($name, $num);
    }

    /**
     * 缓存自减
     * @param string $name 缓存名称
     * @param int $num 数量
     * @return mixed
     */
    public static function dec($name, $num = 0)
    {
        return self::handler()->dec($name, $num);
    }

    /**
     * 删除缓存
     * @param string $name 键值
     * @return bool
     */
    public static function delete($name)
    {
        return CacheStatic::delete($name);
    }

    /**
     * 缓存是否存在
     * @param string $name 键值
     * @return bool
     */
    public static function has($name)
    {
        return self::handler()->has($name);
    }

    /**
     * 清空缓存池
     * @param string $tag 缓存标签
     * @return bool
     */
    public function clear($tag = '')
    {
        return self::handler($tag)->clear();
    }

    /**
     * 获取缓存标签列表
     * @param string $tag 缓存标签
     * @return array
     */
    public static function getTagItems($tag = '')
    {
        return CacheStatic::getTagItems($tag);
    }
}